const http = require('http')
const url = require('url');
function createApplication() {
    const routes = []; // 路由表
    function done(req, res) {
        res.end(`Cannot ${req.method} ${req.url} my`)
    }
    let app = {
        get(path, handler) {
            routes.push({
                path,
                handler,
                method: 'get'
            })
        },
        listen(...args) {
            const server = http.createServer((req, res) => {
                const { pathname: requestPathname, query } = url.parse(req.url, true);
                const requestMethod = req.method.toLowerCase();
                for (let i = 0; i < routes.length; i++) {
                    let { path, handler, method } = routes[i];
                    // 请求的路径和方法都匹配 说明命中了路由
                    if (path === requestPathname && method === requestMethod) {
                        return handler(req, res)
                    }
                }
                // 路由系统中没有匹配到则直接done
                done(req, res)

            });
            server.listen(...args);
        }
    }
    return app
}



module.exports = createApplication